package com.lp.biz.operations.service.impl;
import java.time.LocalDateTime;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lp.biz.category.mapper.BizCategoryMapper;
import com.lp.biz.category.model.entity.BizCategory;
import com.lp.biz.content.mapper.BizCoreContentMapper;
import com.lp.biz.content.model.entity.BizCoreContent;
import com.lp.biz.operations.mapper.BizRecommendBannerMapper;
import com.lp.biz.operations.mapper.BizRecommendItemMapper;
import com.lp.biz.operations.mapper.BizRecommendMapper;
import com.lp.biz.operations.mapper.BizRecommendTodayMapper;
import com.lp.biz.operations.model.entity.BizRecommend;
import com.lp.biz.operations.model.entity.BizRecommendBanner;
import com.lp.biz.operations.model.entity.BizRecommendItem;
import com.lp.biz.operations.model.entity.BizRecommendToday;
import com.lp.biz.operations.model.query.HomeRecommendQuery;
import com.lp.biz.operations.model.query.RecommendContentQuery;
import com.lp.biz.operations.model.vo.*;
import com.lp.biz.operations.service.RecommendService;
import com.lp.common.component.RedisService;
import com.lp.common.entity.PageParams;
import com.lp.common.exception.BaseException;
import com.lp.common.exception.ErrorCodeEnum;
import com.lp.common.utils.CommonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.lp.common.constant.CacheConstant.BIZ_HOME_KEY;
import static com.lp.common.constant.CategoryConstant.*;
import static com.lp.common.constant.CommonConstant.NEGATE;
import static com.lp.common.constant.CommonConstant.SURE;
import static com.lp.common.constant.HomeConstant.*;
import static com.lp.common.constant.RecommendConstant.*;
import static com.lp.common.utils.Tools.copyPage;

/**
 * @program: backend
 * @description:
 * @author: Ke.Song
 * @since: 2024-07-13 1:03:08
 */
@Service
public class RecommendServiceImpl implements RecommendService {

    @Autowired
    private RedisService redis;

    @Autowired
    private BizCategoryMapper categoryMapper;

    @Autowired
    private BizRecommendMapper recommendMapper;

    @Autowired
    private BizCoreContentMapper contentMapper;

    @Autowired
    private BizRecommendTodayMapper todayMapper;

    @Autowired
    private BizRecommendBannerMapper bannerMapper;

    @Autowired
    private BizRecommendItemMapper recommendItemMapper;

    @Override
    public CommonResult getHomeRecommend(HomeRecommendQuery query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        LambdaQueryWrapper<BizRecommend> queryWrapper = new QueryWrapper<BizRecommend>().lambda()
                .eq(BizRecommend::getIsDelete, NEGATE)
                .orderByAsc(BizRecommend::getSort);
        if (StringUtils.isNotBlank(query.getName())) {
            queryWrapper.like(BizRecommend::getName, query.getName());
        }
        if (query.getStatus() != null) {
            if (query.getStatus().equals(SURE) || query.getStatus().equals(NEGATE)) {
                queryWrapper.eq(BizRecommend::getIsDisplay, query.getStatus());
            } else {
                throw new BaseException("状态参数错误");
            }
        }
        if (query.getDisplayAt() != null) {
            queryWrapper.le(BizRecommend::getStartAt, query.getDisplayAt()).ge(BizRecommend::getEndAt, query.getDisplayAt());
        }
        if (query.getParentId() != null) {
            queryWrapper.eq(BizRecommend::getParentId, query.getParentId());
        } else {
            queryWrapper.eq(BizRecommend::getLevel, 1);
        }
        List<BizRecommend> bizRecommends = recommendMapper.selectList(queryWrapper);
        Page<HomeRecommendList> homeRecommendLists = copyPage(new Page<>(), bizRecommends);
        for (BizRecommend bizRecommend : bizRecommends) {
            homeRecommendLists.add(HomeRecommendList.builder(bizRecommend));
        }
        return CommonResult.restPage(homeRecommendLists);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateSort(RecommendSort recommendSort) {
        List<BizRecommend> newSort = new ArrayList<>();
        List<BizRecommend> bizRecommends = recommendMapper.selectList(new QueryWrapper<BizRecommend>().lambda()
                .eq(BizRecommend::getIsDelete, NEGATE).in(BizRecommend::getId, recommendSort.getIds()));
        for (Integer id : recommendSort.getIds()) {
            for (BizRecommend recommend : bizRecommends) {
                if (id.equals(recommend.getId())) {
                    newSort.add(recommend);
                    break;
                }
            }
        }
        if (newSort.size() != bizRecommends.size()) {
            throw new BaseException("数据id输入错误");
        }
        List<BizRecommend> oldSort = recommendMapper.selectList(new QueryWrapper<BizRecommend>().lambda()
                .eq(BizRecommend::getIsDelete, NEGATE).orderByAsc(BizRecommend::getSort)).stream()
                .skip((recommendSort.getPage() - 1L) * recommendSort.getSize()).limit(recommendSort.getSize())
                .toList();
        if (oldSort.size() != newSort.size()) {
            throw new BaseException("页数输入错误");
        }
        for (int i = 0; i < newSort.size(); i++) {
            BizRecommend newRecommend = newSort.get(i);
            BizRecommend oldRecommend = oldSort.get(i);
            if (!newRecommend.getId().equals(oldRecommend.getId())) {
                newRecommend.setSort(oldRecommend.getSort());
                recommendMapper.updateById(newRecommend);
            }
        }
        redis.delete(BIZ_HOME_KEY);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateRecommendStatus(Integer recommendId) {
        BizRecommend recommend = recommendMapper.selectById(recommendId);
        if (recommend == null || recommend.getIsDelete().equals(SURE)) {
            throw new BaseException("推荐位错误");
        }
        if (recommend.getIsDisplay().equals(NEGATE)) {
            recommend.setIsDisplay(SURE);
        } else {
            recommend.setIsDisplay(NEGATE);
        }
        recommendMapper.updateById(recommend);
        redis.delete(BIZ_HOME_KEY);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteRecommend(Integer recommendId) {
        BizRecommend recommend = recommendMapper.selectById(recommendId);
        if (recommend == null) {
            throw new BaseException("推荐位错误");
        }
        recommend.setIsDelete(SURE);
        recommendMapper.updateById(recommend);
        List<BizRecommend> bizRecommends = recommendMapper.selectList(new QueryWrapper<BizRecommend>().lambda().eq(BizRecommend::getParentId, recommend));
        redis.delete(BIZ_HOME_KEY);
        if (bizRecommends.isEmpty()) {
            recommendItemMapper.update(null, new UpdateWrapper<BizRecommendItem>().lambda()
                    .eq(BizRecommendItem::getRecommendId, recommend.getId())
                    .set(BizRecommendItem::getIsDeleted, SURE)
                    .set(BizRecommendItem::getIsDisplay, NEGATE));
        } else {
            Set<Integer> ids = bizRecommends.stream().map(BizRecommend::getId).collect(Collectors.toSet());
            recommendItemMapper.update(null, new UpdateWrapper<BizRecommendItem>().lambda()
                    .in(BizRecommendItem::getRecommendId, ids)
                    .set(BizRecommendItem::getIsDeleted, SURE)
                    .set(BizRecommendItem::getIsDisplay, NEGATE));
            recommendMapper.update(null, new UpdateWrapper<BizRecommend>().lambda()
                    .in(BizRecommend::getId, ids)
                    .set(BizRecommend::getIsDelete, SURE)
                    .set(BizRecommend::getIsDisplay, NEGATE));
        }
        redis.delete(BIZ_HOME_KEY);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void addOrUpdateRecommend(HomeRecommendVo params) {
        checkRecommend(params);
        BizRecommend parentRecommend = null;
        BizRecommend recommend;
        redis.delete(BIZ_HOME_KEY);
        if (params.getId() == null) {
            if (params.getParentId() != null) {
                parentRecommend = recommendMapper.selectById(params.getParentId());
                if (parentRecommend == null || parentRecommend.getIsDelete().equals(SURE) || !parentRecommend.getType().equals(TYPE_MULTILEVEL)) {
                    throw new BaseException("父推荐位错误");
                } else if (params.getType().equals(TYPE_MULTILEVEL)) {
                    throw new BaseException("层级过多");
                }
            }
            recommend = new BizRecommend();
            if (params.getBizCategoryCode() != null) {
                BizCategory category = categoryMapper.selectOne(new QueryWrapper<BizCategory>().lambda()
                        .eq(BizCategory::getCode, params.getBizCategoryCode()));
                if (category == null) {
                    throw new BaseException("分类输入错误");
                }
                recommend.setBizCategoryId(category.getId());
                recommend.setBizCategoryCode(category.getCode());
            }
            recommend.setName(params.getTitle());
            recommend.setType(params.getType());
            recommend.setLevel(parentRecommend == null ? 1 : parentRecommend.getLevel() + 1);
            recommend.setSize(params.getSize() == null || params.getSize() <= 0 ? 5 : params.getSize());
            recommend.setSort(params.getSort() != null ? params.getSort() :
                    recommendMapper.getMaxSort(parentRecommend == null ? null : parentRecommend.getId()));
            recommend.setParentId(params.getParentId());
            recommend.setAlign( params.getAlign() == null ? 1: params.getAlign());
            recommend.setStartAt(params.getStartAt());
            recommend.setEndAt(params.getEndAt());
            recommend.setCreateAt(LocalDateTime.now());
            recommend.setUpdateAt(recommend.getCreateAt());
            recommendMapper.insert(recommend);
        } else {
            recommend = recommendMapper.selectById(params.getId());
            if (recommend == null || recommend.getIsDelete().equals(SURE)) {
                throw new BaseException("推荐位选择错误");
            }
            recommend.setSort(params.getSort() == null ? recommend.getSort() : params.getSort());
            LambdaUpdateWrapper<BizRecommend> updateWrapper = new UpdateWrapper<BizRecommend>().lambda()
                    .eq(BizRecommend::getId, recommend.getId())
                    .set(BizRecommend::getName, params.getTitle())
                    .set(BizRecommend::getSize, params.getSize() == null || params.getSize() <= 0 ? 5 : params.getSize())
                    .set(BizRecommend::getSort, recommend.getSort())
                    .set(BizRecommend::getAlign, params.getAlign() == null ? 1: params.getAlign())
                    .set(BizRecommend::getStartAt, params.getStartAt())
                    .set(BizRecommend::getEndAt, params.getEndAt())
                    .set(BizRecommend::getUpdateAt, LocalDateTime.now());
            recommendMapper.update(null, updateWrapper);
        }
        checkSort(recommend.getId(), recommend.getSort());
        redis.delete(BIZ_HOME_KEY);
    }

    @Override
    public CommonResult getRecommend(Integer recommendId) {
        BizRecommend recommend = recommendMapper.selectById(recommendId);
        if (recommend == null || recommend.getIsDelete().equals(SURE)) {
            throw new BaseException("推荐位错误");
        }
        HomeRecommendVo vo = new HomeRecommendVo();
        vo.setId(recommendId);
        vo.setTitle(recommend.getName());
        vo.setType(recommend.getType());
        vo.setBizCategoryCode(recommend.getBizCategoryCode());
        vo.setStartAt(recommend.getStartAt());
        vo.setEndAt(recommend.getEndAt());
        vo.setSize(recommend.getSize());
        vo.setSort(recommend.getSort());
        vo.setParentId(recommend.getParentId());
        vo.setAlign(recommend.getAlign());
        return CommonResult.success(vo);
    }

    @Override
    public CommonResult getRecommendItems(Integer recommendId, PageParams query) {
        BizRecommend recommend = recommendMapper.selectById(recommendId);
        if (recommend == null || recommend.getIsDelete().equals(SURE)) {
            throw new BaseException("推荐位选择错误");
        }
        PageHelper.startPage(query.getPage(), query.getSize());
        return CommonResult.restPage(recommendItemMapper.getRecommendItems(recommendId));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateRecommendSetting(Integer recommendId, HomeRecommendSetting setting) {
        BizRecommend recommend = recommendMapper.selectById(recommendId);
        if (recommend == null || recommend.getIsDelete().equals(SURE)) {
            throw new BaseException("推荐位选择错误");
        }
        if (setting.getSize() < 1) {
            throw new BaseException("数量输入错误");
        }
        if (setting.getAlign() != 1 && setting.getAlign() != 2) {
            throw new BaseException("排列输入错误");
        }
        recommend.setAlign(setting.getAlign());
        recommend.setSize(setting.getSize());
        redis.delete(BIZ_HOME_KEY);
        recommendMapper.updateById(recommend);
        redis.delete(BIZ_HOME_KEY);
    }

    @Override
    public CommonResult getRecommendContentList(RecommendContentQuery query) {
        CommonResult result;
        if (SOURCE_HOME.equals(query.getSource())) {
            result = getHomeRecommend(query);
        } else if (SOURCE_TODAY.equals(query.getSource())) {
            result = getTodayRecommend(query);
        } else if (SOURCE_BANNER.equals(query.getSource())) {
            result = getBannerRecommend(query);
        } else if (SOURCE_CATEGORY.equals(query.getSource())) {
            result = getCategoryRecommend(query);
        } else {
            throw new BaseException("推荐位来源错误");
        }
        return result;
    }

    @Override
    public CommonResult getRecommendTextList(RecommendContentQuery query) {
        BizRecommend recommend = recommendMapper.selectById(query.getRecommendId());
        if (recommend == null || recommend.getIsDelete().equals(SURE) || !recommend.getBizCategoryCode().equals(CODE_FAMOUS_REMARK)) {
            throw new BaseException("推荐位输入错误");
        }
        List<BizCoreContent> bizCoreContents  = new ArrayList<>(6);
        List<BizRecommendItem> items = new ArrayList<>(6);
        Page<RecommendContent> result = getBizCoreContent(recommend, query, items, bizCoreContents);
        for (BizCoreContent content : bizCoreContents) {
            RecommendContent recommendContent = new RecommendContent();
            recommendContent.setId(content.getId());
            recommendContent.setIsAdd(NEGATE);
            recommendContent.setContent(content.getContent());
            recommendContent.setBizCategoryCode(recommend.getBizCategoryCode());
            recommendContent.setSource(query.getSource());
            for (BizRecommendItem item : items) {
                if (item.getBizContentId().equals(content.getId())) {
                    recommendContent.setIsAdd(SURE);
                    break;
                }
            }
            result.add(recommendContent);
        }
        return CommonResult.restPage(result);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void addRecommendItem(HomeRecommendItemAddVo vo) {
        if (vo.getContentId() == null) {
            throw new BaseException("内容不能为空");
        }
        BizRecommend recommend = recommendMapper.selectById(vo.getRecommendId());
        if (recommend == null || recommend.getIsDelete().equals(SURE)) {
            throw new BaseException("推荐位输入错误");
        }
        BizCoreContent content = contentMapper.selectById(vo.getContentId());
        if (content == null || content.getIsDisplay().equals(NEGATE) || content.getIsDeleted().equals(SURE)
                || !recommend.getBizCategoryCode().equals(content.getBizCategoryCode())) {
            throw new BaseException("内容输入错误");
        }
        BizRecommendItem item = new BizRecommendItem();
        item.setRecommendId(recommend.getId());
        item.setBizContentId(content.getId());
        item.setCreateAt(LocalDateTime.now());
        redis.delete(BIZ_HOME_KEY);
        recommendItemMapper.insert(item);
        redis.delete(BIZ_HOME_KEY);
    }

    @Override
    public void addRecommendTextItem(HomeRecommendItemAddVo vo) {
        if (vo.getContentIds() == null || vo.getContentIds().isEmpty()) {
            throw new BaseException("内容不能为空");
        }
        BizRecommend recommend = recommendMapper.selectById(vo.getRecommendId());
        if (recommend == null || recommend.getIsDelete().equals(SURE)) {
            throw new BaseException("推荐位输入错误");
        }
        long l = contentMapper.selectCount(new QueryWrapper<BizCoreContent>().lambda()
                .eq(BizCoreContent::getBizCategoryCode, CODE_FAMOUS_REMARK)
                .in(BizCoreContent::getId, vo.getContentIds())
                .eq(BizCoreContent::getIsDisplay, SURE)
                .eq(BizCoreContent::getIsDeleted, NEGATE));
        if (vo.getContentIds().size() != l) {
            throw new BaseException("内容输入错误");
        }
        Set<Integer> exitsIds = new HashSet<>(6);
        for (BizRecommendItem item : recommendItemMapper.selectList(new QueryWrapper<BizRecommendItem>().lambda()
                .eq(BizRecommendItem::getRecommendId, vo.getRecommendId()).eq(BizRecommendItem::getIsDeleted, NEGATE))) {
            exitsIds.add(item.getBizContentId());
        }
        redis.delete(BIZ_HOME_KEY);
        for (Integer contentId : vo.getContentIds()) {
            if (!exitsIds.contains(contentId)) {
                BizRecommendItem item = new BizRecommendItem();
                item.setRecommendId(vo.getRecommendId());
                item.setBizContentId(contentId);
                item.setCreateAt(LocalDateTime.now());
                recommendItemMapper.insert(item);
            }
        }
        redis.delete(BIZ_HOME_KEY);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteRecommendItem(Integer itemId) {
        BizRecommendItem item = recommendItemMapper.selectById(itemId);
        if (item == null) {
            throw new BaseException(ErrorCodeEnum.PARAMS_ERROR);
        }
        item.setIsDisplay(NEGATE);
        item.setIsDeleted(SURE);
        redis.delete(BIZ_HOME_KEY);
        recommendItemMapper.updateById(item);
        redis.delete(BIZ_HOME_KEY);
    }

    private CommonResult getHomeRecommend(RecommendContentQuery query) {
        if (query.getRecommendId() == null) {
            throw new BaseException("资源id不能为空");
        }
        BizRecommend recommend = recommendMapper.selectById(query.getRecommendId());
        if (recommend == null || recommend.getIsDelete().equals(SURE) || recommend.getType().equals(TYPE_MULTILEVEL)) {
            throw new BaseException("推荐位输入错误");
        }
        List<BizCoreContent> bizCoreContents  = new ArrayList<>(6);
        List<BizRecommendItem> items = new ArrayList<>(6);
        Page<RecommendContent> result = getBizCoreContent(recommend, query, items, bizCoreContents);
        for (BizCoreContent content : bizCoreContents) {
            RecommendContent builder = RecommendContent.builder(content);
            builder.setSource(query.getSource());
            for (BizRecommendItem item : items) {
                if (item.getBizContentId().equals(content.getId())) {
                    builder.setIsAdd(SURE);
                    break;
                }
            }
            result.add(builder);
        }
        return CommonResult.restPage(result);
    }

    private CommonResult getTodayRecommend(RecommendContentQuery query) {
        LambdaQueryWrapper<BizCoreContent> queryWrapper = new QueryWrapper<BizCoreContent>().lambda()
                .eq(BizCoreContent::getIsDeleted, NEGATE)
                .eq(BizCoreContent::getIsDisplay, SURE)
                .orderByAsc(BizCoreContent::getCreateAt);
        String code = query.getBizCategoryCode();
        if (code != null) {
            if (!code.equals(CODE_READING) && !code.equals(CODE_STORY)) {
                throw new BaseException("分类输入错误");
            }
            queryWrapper.eq(BizCoreContent::getBizCategoryCode, code);
        } else {
            queryWrapper.in(BizCoreContent::getBizCategoryCode, CODE_READING, CODE_STORY);
        }
        if (query.getTitle() != null && StringUtils.isNotBlank(query.getTitle())) {
            queryWrapper.like(BizCoreContent::getTitle, query.getTitle());
        }
        List<BizRecommendToday> todayList = todayMapper.selectList(new QueryWrapper<BizRecommendToday>().lambda()
                .eq(BizRecommendToday::getIsDelete, NEGATE));
        PageHelper.startPage(query.getPage(), query.getSize());
        List<BizCoreContent> bizCoreContents = contentMapper.selectList(queryWrapper);
        Page<RecommendContent> result = copyPage(new Page<>(), bizCoreContents);
        for (BizCoreContent content : bizCoreContents) {
            RecommendContent builder = RecommendContent.builder(content);
            builder.setSource(query.getSource());
            for (BizRecommendToday item : todayList) {
                if (item.getBizContentId().equals(content.getId())) {
                    builder.setIsAdd(SURE);
                    break;
                }
            }
            result.add(builder);
        }
        return CommonResult.restPage(result);
    }

    private CommonResult getBannerRecommend(RecommendContentQuery query) {
        LambdaQueryWrapper<BizCoreContent> queryWrapper = new QueryWrapper<BizCoreContent>().lambda()
                .eq(BizCoreContent::getIsDeleted, NEGATE)
                .eq(BizCoreContent::getIsDisplay, SURE)
                .orderByAsc(BizCoreContent::getCreateAt);
        String code = query.getBizCategoryCode();
        if (code != null) {
            if (!code.equals(CODE_READING) && !code.equals(CODE_STORY) && !code.equals(CODE_TRAINING)) {
                throw new BaseException("分类输入错误");
            }
            queryWrapper.eq(BizCoreContent::getBizCategoryCode, code);
        } else {
            queryWrapper.in(BizCoreContent::getBizCategoryCode, CODE_READING, CODE_STORY, CODE_TRAINING);
        }
        if (query.getTitle() != null && StringUtils.isNotBlank(query.getTitle())) {
            queryWrapper.like(BizCoreContent::getTitle, query.getTitle());
        }
        List<BizRecommendBanner> bannerList = bannerMapper.selectList(new QueryWrapper<BizRecommendBanner>().lambda()
                .eq(BizRecommendBanner::getIsDelete, NEGATE));
        PageHelper.startPage(query.getPage(), query.getSize());
        List<BizCoreContent> bizCoreContents = contentMapper.selectList(queryWrapper);
        Page<RecommendContent> result = copyPage(new Page<>(), bizCoreContents);
        for (BizCoreContent content : bizCoreContents) {
            RecommendContent builder = RecommendContent.builder(content);
            builder.setSource(query.getSource());
            for (BizRecommendBanner item : bannerList) {
                if (item.getIsExternal().equals(NEGATE) && item.getBizContentId().equals(content.getId())) {
                    builder.setIsAdd(SURE);
                    break;
                }
            }
            result.add(builder);
        }
        return CommonResult.restPage(result);
    }

    private CommonResult getCategoryRecommend(RecommendContentQuery query) {
        LambdaQueryWrapper<BizCoreContent> queryWrapper = new QueryWrapper<BizCoreContent>().lambda()
                .eq(BizCoreContent::getIsDeleted, NEGATE)
                .eq(BizCoreContent::getIsDisplay, SURE)
                .orderByDesc(BizCoreContent::getCreateAt);
        String code = query.getBizCategoryCode();
        if (code == null) {
            queryWrapper.in(BizCoreContent::getBizCategoryCode, CODE_READING, CODE_STORY, CODE_TRAINING);
        } else if (!code.equals(CODE_READING) && !code.equals(CODE_STORY) && !code.equals(CODE_TRAINING)) {
            throw new BaseException("分类输入错误");
        } else {
            queryWrapper.eq(BizCoreContent::getBizCategoryCode, code);
        }
        PageHelper.startPage(query.getPage(), query.getSize());
        List<BizCoreContent> bizCoreContents = contentMapper.selectList(queryWrapper);
        Page<RecommendContent> recommendContents = copyPage(new Page<>(), bizCoreContents);
        for (BizCoreContent content : bizCoreContents) {
            RecommendContent builder = RecommendContent.builder(content);
            builder.setSource(query.getSource());
            builder.setIsRecommend(content.getIsRecommend() == null ? NEGATE : content.getIsRecommend());
            builder.setIsAdd(content.getIsRecommend() == null ? NEGATE : content.getIsRecommend());
            recommendContents.add(builder);
        }
        return CommonResult.restPage(recommendContents);
    }

    private Page<RecommendContent> getBizCoreContent(BizRecommend recommend, RecommendContentQuery query,
                                                     List<BizRecommendItem> items, List<BizCoreContent> bizCoreContents) {
        items.addAll(recommendItemMapper.selectList(new QueryWrapper<BizRecommendItem>().lambda()
                .eq(BizRecommendItem::getRecommendId, recommend.getId()).eq(BizRecommendItem::getIsDeleted, NEGATE)));
        PageHelper.startPage(query.getPage(), query.getSize());
        LambdaQueryWrapper<BizCoreContent> queryWrapper = new QueryWrapper<BizCoreContent>().lambda()
                .eq(BizCoreContent::getIsDeleted, NEGATE)
                .eq(BizCoreContent::getIsDisplay, SURE)
                .eq(recommend.getBizCategoryId() != null, BizCoreContent::getBizCategoryId, recommend.getBizCategoryId())
                .orderByAsc(BizCoreContent::getCreateAt);
        if (query.getContent() != null && StringUtils.isNotBlank(query.getContent())) {
            queryWrapper.like(BizCoreContent::getContent, query.getContent());
        }
        if (query.getTitle() != null && StringUtils.isNotBlank(query.getTitle())) {
            queryWrapper.like(BizCoreContent::getTitle, query.getTitle());
        }
        List<BizCoreContent> tempPage = contentMapper.selectList(queryWrapper);
        bizCoreContents.addAll(tempPage);
        return copyPage(new Page<>(), tempPage);
    }

    private void checkRecommend(HomeRecommendVo params) {
        Integer type = params.getType();
        String code = params.getBizCategoryCode();
        if (type.equals(TYPE_IMG)) {
            if (code == null) {
                throw new BaseException("分类不能为空");
            } else if (!code.equals(CODE_READING) && !code.equals(CODE_TRAINING) && !code.equals(CODE_COURSE)) {
                throw new BaseException("图文类型只能选择共读会或训练营");
            }
        } else if (type.equals(TYPE_TEXT)) {
            if (code == null) {
                throw new BaseException("分类不能为空");
            } else if (!code.equals(CODE_STORY) && !code.equals(CODE_FAMOUS_REMARK)) {
                throw new BaseException("文本类型只能选择听故事或名人名言");
            }
        } else if (type.equals(TYPE_MULTILEVEL)) {
            params.setBizCategoryCode(null);
        } else {
            throw new BaseException("类型错误");
        }
        if (params.getAlign() != null) {
            if (params.getAlign() != 1 && params.getAlign() != 2) {
                throw new BaseException("排列方向错误");
            }
        }
    }

    private void checkSort(Integer recommendId, Integer sort) {
        List<BizRecommend> bizRecommends = recommendMapper.selectList(new QueryWrapper<BizRecommend>().lambda().eq(BizRecommend::getSort, sort));
        if (bizRecommends.size() > 1) {
            recommendMapper.updateSort(sort, recommendId);
            bizRecommends = bizRecommends.stream().filter(o -> !o.getId().equals(recommendId))
                    .sorted(Comparator.comparing(BizRecommend::getCreateAt)).toList();
            if (!bizRecommends.isEmpty()) {
                checkSort(bizRecommends.get(0).getId(), sort + 1);
            }
        }
    }
}
